package src.com.qf.utils;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class JdbcUtil {
    private static DruidDataSource ds=null;
    private static final ThreadLocal<Connection> th=new ThreadLocal<>();

    static{
        Properties p=new Properties();
        InputStream in = JdbcUtil.class.getResourceAsStream("/jdbc.properties");
        try {
            p.load(in);
            ds  = (DruidDataSource) DruidDataSourceFactory.createDataSource(p);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }




    public static Connection getCon(){
        Connection con=null;
        con=th.get();
        if(con==null){
            try {
                con=ds.getConnection();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            th.set(con);
        }
        return con;
    }


    /**
     * 开启事务
     */
    public static void begin() throws SQLException {
        Connection con=getCon();
        con.setAutoCommit(false);
    }

    /**
     * 提交事务
     * @throws SQLException
     */
    public static void commit() {
        Connection con=getCon();
        try {
            con.commit();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            close(con,null,null);
        }
    }


    /**
     * 回滚
     * @throws SQLException
     */
    public static void rollback() {
        Connection con=getCon();
        try {
            con.rollback();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            close(con,null,null);
        }
    }


    /**
     * 关闭操作
     * @param con
     * @param sta
     * @param rs
     * @throws SQLException
     */
    public static void close(Connection con, Statement sta, ResultSet rs)  {
        if(con!=null){
            try {
                con.close();
                th.remove();//不要忘记将th清空
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(sta!=null){
            try {
                sta.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(rs!=null){
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
